package com.system.weirdor.www.controller;

import com.system.weirdor.common.advice.BaseController;
import com.system.weirdor.common.utills.CaptchaUtil;
import com.system.weirdor.common.utills.IPUtils;
import com.system.weirdor.module.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by weirdor on 2017/8/24.
 */
@Controller
@RequestMapping("/api/u")
public class AccountController extends BaseController {

    @Autowired
    private IUserService userService;

    @ResponseBody
    @RequestMapping(value = "/signIn", method = RequestMethod.POST)
    public Object login(HttpServletRequest request, @RequestParam(value = "username")  String username,
                        @RequestParam(value = "password") String password, @RequestParam(value = "verify")String verify) {

        Map<String, Object> map = new HashMap<String, Object>();
        System.out.println("username:" + username + "----" + "password:" + password);
        String verifyCode = String.valueOf(request.getSession().getAttribute("verify"));
        System.out.println(verify+"-------"+verifyCode);

        if (!verifyCode.toLowerCase().equalsIgnoreCase(verify.toLowerCase())) {
            map.put("code", "400");
            map.put("msg", "验证码错误");
            return map;
        }
        request.getSession().removeAttribute("verify");
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
            // 验证是否登录成功
            if (subject.isAuthenticated()) {
                request.getSession().setAttribute("username", username);
                System.out.println(   IPUtils.getIpAddr(request));
                System.out.println("用户[" + username + "]登录认证通过(这里可以进行一些认证通过后的一些系统参数初始化操作)");
                map.put("code", 200);
                map.put("msg", "登录成功");
                System.out.println(request.getSession().getAttribute("username"));
            } else {
                token.clear();
            }
        } catch (UnknownAccountException e) {
            map.put("code", 400);
            map.put("msg", "用户名不存在");
            logger.info("用户名不存在");
        } catch (IncorrectCredentialsException e) {
            map.put("code", 400);
            map.put("msg", "用户名/密码错误");
            logger.info("用户名/密码错误");
        } catch (ExcessiveAttemptsException e) {
            map.put("code", 400);
            map.put("msg", "登录失败多次，账户锁定10分钟");
            // TODO: handle exception
            logger.info("登录失败多次，账户锁定10分钟");
        }
        catch(LockedAccountException e){
            map.put("code", 400);
            map.put("msg", "账户被锁定");
            // 其他错误，比如锁定，如果想单独处理请单独catch处理
            logger.info("账户被锁定");
        }
        catch (AuthenticationException e) {
            map.put("code", 400);
            map.put("msg", "其他错误");
            // 其他错误，比如锁定，如果想单独处理请单独catch处理
            logger.info("其他错误：" + e.getMessage());
        }
        return map;
    }

    /**
     * 登录页面验证码
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/signIn/captcha", method = RequestMethod.GET)
    public void verify(HttpServletRequest request, HttpServletResponse response) {
        try {
            String verifyCode = CaptchaUtil.outputImage(response.getOutputStream());
            request.getSession().setAttribute("verify", verifyCode);//把验证码存入session
            System.out.println("验证码:"+verifyCode);
            logger.debug(String.format("verify code: %s", verifyCode));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
